package com.htfyun.ft.fragment.engineer;

import android.os.Bundle;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Switch;

import androidx.annotation.Nullable;

import com.htfyun.ft.R;
import com.htfyun.ft.fragment.BaseFragment;
import com.htfyun.hardware.NightDisplayController;

/**
 * Created by sst on 2018/7/11.
 */

public class FragmentNightDisplay extends BaseFragment
        implements NightDisplayController.Callback,
        CompoundButton.OnCheckedChangeListener,
        SeekBar.OnSeekBarChangeListener {

    private final static String TAG = FragmentNightDisplay.class.getSimpleName();

    private Switch switchEnabled;
    private SeekBar seekBar;
    private NightDisplayController mController;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_engineer_night_display;
    }

    @Override
    protected void onInitView(@Nullable Bundle savedInstanceState) {

        switchEnabled = (Switch) findViewById(R.id.switchEnabled);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        mController = new NightDisplayController(mContext);

        seekBar.setMax(convertTemperature(mController.getMinimumColorTemperature()));

    }

    @Override
    protected void onVisible() {
        super.onVisible();
        mController.setListener(this);

        switchEnabled.setOnCheckedChangeListener(this);
        seekBar.setOnSeekBarChangeListener(this);

        onActivated(mController.isActivated());
        onColorTemperatureChanged(mController.getColorTemperature());
    }

    @Override
    protected void onInvisible() {
        super.onInvisible();
        mController.setListener(null);
    }

    /**
     * Inverts and range-adjusts a raw value from the SeekBar (i.e. [0, maxTemp-minTemp]), or
     * converts an inverted and range-adjusted value to the raw SeekBar value, depending on the
     * adjustment status of the input.
     */
    private int convertTemperature(int temperature) {
        return mController.getMaximumColorTemperature() - temperature;
    }


    @Override
    public void onActivated(boolean activated) {
        switchEnabled.setChecked(activated);
        seekBar.setEnabled(activated);
    }

    @Override
    public void onColorTemperatureChanged(int colorTemperature) {
        seekBar.setProgress(convertTemperature(colorTemperature));
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        mController.setActivated(isChecked);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.e(TAG, "progress = " + progress);
        if (fromUser) {
            mController.setColorTemperature(convertTemperature(progress));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
